<?php

namespace app\common\model\xilujob;

use think\Db;
use think\Exception;
use think\Log;
use think\Model;

class CompanyViewLog extends Model
{
    protected $name = 'xilujob_company_view_log';
    protected $autoWriteTimestamp = 'int';


    protected $createTime = 'createtime';
    protected $updateTime = false;

    /**
     * 查看课程
     * @param int $userId
     * @param int $companyId
     * @return
     */
    public static function viewCompany($userId, $companyId) {
        if(!$userId || !$companyId) {
            throw new Exception(__('invalid arguments'));
        }
        Db::startTrans();
        try {
            $record = static::where('user_id',$userId)->where('company_id', $companyId)->find();
            $now = time();
            if(!$record) {
                $record = new static();
                $record->save(['user_id'=>$userId,'company_id'=>$companyId,'view_time'=>$now]);
                CompanyStatistics::where('company_id',$companyId)->failException(true)->update(['view_count'=>Db::raw('view_count+1')]);
            }else {
                //两小时内不重复加
                $data = ['view_time'=>time()];
                if($now>$record->view_time+3600*2) {
                    $data['view_count'] = Db::raw('view_count+1');
                }
                $record->save($data);
            }
            Db::commit();
            return true;
        }catch (\Exception $e) {
            Log::error($e->getMessage()."\n".$e->getTraceAsString());
            throw $e;
        }
    }

}
